package wangjg.xuexiban.activity.category;

import java.io.File;

import wangjg.xuexiban.R;
import wangjg.xuexiban.activity.web.WebViewActivity;
import wangjg.xuexiban.data.CategoryDAO;
import wangjg.xuexiban.entity.Category;
import wangjg.xuexiban.util.Constant;
import wangjg.xuexiban.widget.file.FileSelectorActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class EditableCategoryActivity extends BasicCategoryActivity {
	protected CategoryDAO categoryDAO = new CategoryDAO();
	
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 1, R.string.download_newcard);
		menu.add(0, 2, 2, "创建");
		menu.add(0, 3, 3, "退出");
		return super.onCreateOptionsMenu(menu);
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==1){
			this.openDownloadWeb();
		}else if(item.getItemId()==2){
			openCategoryEdit(null);
		}else if(item.getItemId()==3){
			this.finish();
		}
		return super.onOptionsItemSelected(item);
	}
	
	protected void openDownloadWeb() {
		Intent intent = new Intent(this, WebViewActivity.class);
		intent.putExtra("url", Constant.DEFAULT_DOWN_URL);
		startActivity(intent);
	}
	
	protected View getCategoryView(Category category) {
		View view = super.getCategoryView(category);
		view.setOnLongClickListener(new LCL());
		return view;
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		String filepath = null;
		Bundle bundle = null;
		if (data != null && (bundle = data.getExtras()) != null) {
			filepath = bundle.getString("path");
		}
		if(filepath==null){
			return ;
		}
		if(requestCode==1){
			ImageView category_img = (ImageView) editView.findViewById(R.id.category_photo);
			if (filepath!=null&&filepath.length()>0) {
				Bitmap bitmap = rc.get(filepath);
				category_img.setImageBitmap(bitmap);
				category_img.setTag(filepath);
			}
		}else if(requestCode==2){
		}
	}

	private View editView;
	
	private View getEditView(final Category category){
		editView = this.inflate(R.layout.category_edit);
		ImageView category_img = (ImageView) editView.findViewById(R.id.category_photo);
		EditText editText = (EditText) editView.findViewById(R.id.name_edit);
		editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
		category_img.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Intent intent = new Intent(EditableCategoryActivity.this, FileSelectorActivity.class);
				if(category!=null){
					File img_file = new File(category.getUuid(), category.getPhoto());
					intent.putExtra("path", img_file.getPath());
				}
				startActivityForResult(intent, 1);
			}});
		
		if(category!=null){
			final File img_file = new File(category.getUuid(), category.getPhoto());
			if (img_file.exists() && img_file.isFile()) {
				Bitmap bitmap = rc.get(img_file.getPath());
				category_img.setImageBitmap(bitmap);
			}
		}
		if(category!=null){
			editText.setText(category.getName());
		}
		
		editView.setTag(category);
		return editView;
	}
	
	private void saveCategoryEdit(){
		ImageView category_img = (ImageView) editView.findViewById(R.id.category_photo);
		EditText editText = (EditText) editView.findViewById(R.id.name_edit);
		Category category = (Category) this.editView.getTag();
		if(category==null){
			if(editText.length()==0 && category_img.getTag()==null){
				return;
			}
			category = new Category();
		}
		category.setName(editText.getText().toString());
		if(category_img.getTag()!=null){
			category.setPhoto((String)category_img.getTag());
		}
		if(category.getUuid()==null){
			String categoryName = Constant.CUSTOM_CATEGORY + System.currentTimeMillis();
			category.setUuid(categoryName);	
		}
		this.categoryDAO.save(category);
		this.onStart();
	}
	
	private void deleteCategory(){
		Category category = (Category) this.editView.getTag();
		this.categoryDAO.delete(category);
		this.onStart();
	}

	private void openCategoryEdit(Category category){
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("修改目录");
		builder.setView(getEditView(category));
		LCL lcl = new LCL();
		builder.setPositiveButton("保存",lcl);
		if(category!=null)
			builder.setNeutralButton("删除", lcl);
        builder.setNegativeButton("取消", lcl);
		builder.show();
	}
	
	protected void onStart() {
		super.onStart();
	}
	
	private void openDownloadDialog() {
		new AlertDialog.Builder(
				EditableCategoryActivity.this)
                .setTitle("提醒")
                .setMessage("你还没有下载内容，点击确定下载")
                .setPositiveButton(
                        "确定",
                        new DialogInterface.OnClickListener() {  
                            public void onClick(DialogInterface dialog,int which) {  
                            	openDownloadWeb();
                            }  
                        })
                .setNegativeButton(
                        "取消",
                        new DialogInterface.OnClickListener(){
                            public void onClick(DialogInterface dialog,int which) {  
                                // 这里点击取消之后可以进行的操作   
                            }
                        }).show();
	}

	void openDownloadDialog1() {
		new AlertDialog.Builder(this)
				.setTitle("选择")
				.setItems(new String[] { "第一个", "第二个", "第三个" },
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichcountry) {
								Toast.makeText(EditableCategoryActivity.this,"你选择了 " + whichcountry,Toast.LENGTH_SHORT).show();
							}
						})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface d, int which) {
						d.dismiss();
					}
				}).show();
	}
	
	class LCL implements OnLongClickListener, DialogInterface.OnClickListener{
		public LCL() {
		}

		public boolean onLongClick(View v) {
			openCategoryEdit((Category)v.getTag());
			return false;
		}

		public void onClick(DialogInterface dialog, int which) {
        	if(which==DialogInterface.BUTTON_POSITIVE){
        		saveCategoryEdit();
        	}else if(which==DialogInterface.BUTTON_NEUTRAL){//del
        		AlertDialog.Builder builder = new AlertDialog.Builder(context);
        		builder.setTitle("确定删除吗");
        		builder.setPositiveButton("删除",new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int which) {
						deleteCategory();
					}
        		});
                builder.setNegativeButton("取消", null);
        		builder.show();
        	}
		}
	}

}
